/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jdesktop.wonderland.modules.kinectcontrol.client.threads;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.wonderland.client.jme.JmeClientMain;
import org.jdesktop.wonderland.modules.contentrepo.client.ContentRepository;
import org.jdesktop.wonderland.modules.contentrepo.common.ContentCollection;
import org.jdesktop.wonderland.modules.contentrepo.common.ContentRepositoryException;
import org.jdesktop.wonderland.modules.contentrepo.common.ContentResource;

/**
 * Responsible for dispatching regestered gestures
 * 
 * @author Dominik
 */
public class KeyPressDispatcher {
    
    private Map<String,Integer[]> keyMapping;
    private Map<Integer[],KeyPress> threadPool;
    private static final Logger LOGGER =
            Logger.getLogger(JmeClientMain.class.getName());
       
    /**
     * Constructor for loading the keymapping from the server.
     * This allows to add more gesture than the default allows
     * 
     * @param fileLocation  Location of the file on the OWL repository (from root)
     * @param repo          Repository connection
     */
    public KeyPressDispatcher(String fileLocation, ContentRepository repo)
    {
        //Create Instances of Maps
        keyMapping = new HashMap<String, Integer[]>();
        threadPool = new HashMap<Integer[], KeyPress>();
        
        loadKeyMapping(fileLocation, repo);
    } 
    
    /**
     * Descides what need to be done with the gestures that haven been recognized
     * TODO Load available gestures through file and dispatch dynamically
     * 
     * @param gesture 
     */
    public void gestureEventRegestered(String gesture)
    {   
        
        KeyPress keyPresser = null;
        
        if(keyMapping.containsKey(gesture.trim()))
        {
            Integer[] key = keyMapping.get(gesture.trim());
            
            //Check if thread nees to be created
            if(!threadPool.containsKey(key))
            {
                //create new instance of thread class
                keyPresser = new KeyPress(key,false, key[3].intValue());
                threadPool.put(key, keyPresser);
            }
            else
            {
                //Retrive thread class from pool
                keyPresser = threadPool.get(key);
                
                if(!keyPresser.isAlive())
                {
                    keyPresser = new KeyPress(key,false, key[3].intValue());
                    threadPool.remove(key);
                    threadPool.put(key,keyPresser);
                }
            }
            
            //Check if thread is still running
            //Wenn it isn't running start it again
            if(!keyPresser.isRunning())
            {
                keyPresser.start();
            }
        }
    }
    
    private void loadKeyMapping(String fileLocation, ContentRepository repo)
    {
        String line;
        BufferedReader br = null;
        
        //For reading from Repo
        ContentResource current = null;
        ContentCollection ccr = null;
        
        try{
            // Read the file and display it line by line.
            ccr = repo.getRoot();
            current = (ContentResource)ccr.getChild(fileLocation);
            br = new BufferedReader(new InputStreamReader(current.getInputStream()));


            while ((line = br.readLine()) != null)
            {
                String[]results = line.split("=");
                String[]values = results[1].split(";");
                
                Integer[] intArray = {Integer.parseInt(values[0]),
                                      Integer.parseInt(values[1]),
                                      Integer.parseInt(values[2]),
                                      Integer.parseInt(values[3])};
                
                keyMapping.put(results[0], intArray);
            }
        }
        catch(ContentRepositoryException ex)
        {
            LOGGER.logp(Level.SEVERE, this.getClass().getName(), "loadKeyMapping", "Error in accessing content repository");
        }
        catch(IOException ex)
        {
            LOGGER.logp(Level.SEVERE, this.getClass().getName(), "loadKeyMapping", "Error in reading file");
        }
    }           
}
